<script setup lang="ts">
import { computed } from 'vue';
import type { Todo } from '@/types';

const props = defineProps<{
  todo: Todo;             
  editingId: number | null; 
  editText: string;         
}>();

const emit = defineEmits<{
  (e: 'toggle-status', id: number): void;  
  (e: 'delete', id: number): void;             
  (e: 'start-edit', todo: Todo): void;        
  (e: 'finish-edit', id: number, content: string): void; 
  (e: 'cancel-edit'): void;                     
  (e: 'update-edit-text', value: string): void; 
}>();


const isEditing = computed(() => props.editingId === props.todo.id);

// 开始编辑
const handleStartEdit = () => {
  emit('start-edit', props.todo);
};

// 完成编辑
const handleFinishEdit = () => {
  const trimmedContent = props.editText.trim();
  if (trimmedContent && isEditing.value) {
    emit('finish-edit', props.todo.id, trimmedContent);
  }
  emit('cancel-edit'); 
};

// 取消编辑
const handleCancelEdit = () => {
  emit('cancel-edit');
};

const handleInput = (e: Event) => {
  const target = e.target as HTMLInputElement;
  emit('update-edit-text', target.value);
};
</script>

<template>
  <div class="todo-content" :class="{ 'todo-done': todo.isDone }">
    <!-- 编辑状态 -->
    <template v-if="isEditing">
      <input
        type="text"
        :value="editText"
        @input="handleInput"
        @blur="handleFinishEdit"
        @keyup.enter="handleFinishEdit"
        @keyup.esc="handleCancelEdit"
        autofocus
        :aria-label="`edit-input-${todo.id}`"
      >
    </template>
    <!-- 普通状态 -->
    <template v-else>
      <span @dblclick="handleStartEdit">{{ todo.content }}</span>
    </template>
  </div>

  <div class="todo-list-btns">
    <!-- 切换完成状态 -->
    <button class="status-btn" @click="emit('toggle-status', todo.id)">
      <span>✓</span>
    </button>
    <!-- 删除待办 -->
    <button class="status-btn" @click="emit('delete', todo.id)">
      <span>✕</span>
    </button>
    <button
      class="edit-btn"
      @click="handleStartEdit"
      v-if="!isEditing"
    >
      <span>修改</span>
    </button>
  </div>
</template>

<style scoped>
.todo-content {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 16px;
  overflow: hidden
}

.todo-done {
  color: #de541e;
  text-decoration: line-through;
}

.todo-list-btns {
  display: flex;
  gap: 8px;
}

.status-btn, .edit-btn {
  padding: 4px 10px;
  font-size: 14px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.todo-list-btns button:nth-child(2) {
  background-color: #ff4444 !important;
}

.todo-list-btns button:nth-child(2):hover {
  background-color: #cc0000 !important;
}

/* 编辑输入框样式 */
.todo-content input[type="text"] {
  flex: 1;
  padding: 6px 8px;
  font-size: 16px;
  border: 1px solid #42b983;
  border-radius: 4px;
  outline: none;
  margin-right: 10px;
}
</style>